import request from '@/utils/request'

export default class GridApiService {
  constructor(url, params = {}) {
    this.baseUrl = url
    this.params = params
  }

  bindParams(params) {
    if (!params) {
      params = {}
    }
    return Object.assign({}, this.params, params)
  }

  // 获取列表数据
  options() {
    return request({
      url: this.baseUrl + '/options',
      method: 'GET'
    })
  }

  // 获取列表数据
  config(params) {
    return request({
      url: this.baseUrl + '/index',
      method: 'GET',
      params: this.bindParams(params)
    })
  }

  // 获取列表数据
  list(query) {
    return request({
      url: this.baseUrl + '/list',
      method: 'GET',
      params: this.bindParams(query)
    })
  }

  // 获取数据详情
  view(id) {
    return request({
      url: this.baseUrl + '/view',
      method: 'GET',
      params: this.bindParams({
        id: id
      })
    })
  }

  // 新增数据
  create(data, params = {}, postMethod = true) {
    return request({
      url: this.baseUrl + '/create',
      method: postMethod ? 'POST' : 'GET',
      params: this.bindParams(params),
      data: data
    })
  }

  // 修改数据
  update(data = null, id = null, postMethod = true) {
    var params = {
      id: id
    }
    if (!postMethod && data) {
      params = { ...data, ...params }
    }
    return request({
      url: this.baseUrl + '/update',
      params: this.bindParams(params),
      data: data,
      method: postMethod ? 'POST' : 'GET'
    })
  }

  // 删除数据
  delete(id) {
    return request({
      url: this.baseUrl + '/delete',
      params: this.bindParams({
        id: id
      }),
      method: 'POST'
    })
  }

  // 扩展操作
  handleAction(name, id, data = null) {
    var params = {}
    if (id) {
      params = {
        id: id
      }
    }
    return request({
      url: this.baseUrl + '/' + name,
      params: this.bindParams(params),
      data: data,
      method: 'POST'
    })
  }
}
